package com.ptbuy.update;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;


import com.ptbuy.utils.Constants;
import com.ptbuy.utils.Utils;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class UpdateTask extends AsyncTask<String, Void, Void> {

    private ProgressDialog progressDialog;
    private int mType;
    private String description;
    public static final int AUTO = 1;
    public static final int MANU = 0;

    public UpdateTask(int type) {
        mType = type;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (mType == 0) {
            progressDialog = new ProgressDialog(Constants.CurrentContext);
            progressDialog.setCancelable(false);
            progressDialog.setTitle("检查更新");
            progressDialog.setIcon(android.R.drawable.ic_dialog_alert);
            progressDialog.setMessage("正在检查更新，请等待...");
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    cancel(true);
                    Toast.makeText(Constants.CurrentContext, "检查更新失败", Toast.LENGTH_LONG).show();
                }
            });
            progressDialog.show();
        }
    }

    @Override
    protected Void doInBackground(String... params) {
        try {
            String url = Constants.UPDATE_URL;
            getVersionId(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if (Constants.DOWNLOAD_URL.equals("EMPTY")) {
            if (mType == 0) {
                progressDialog.dismiss();
                new AlertDialog.Builder(Constants.CurrentContext)
                        .setTitle("警告")
                        .setMessage("检查更新失败，请检查网络设置！")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
        } else {
            String versionID = Utils.getVersion();
            if (versionID != null) {
                if (versionID.compareTo(Constants.VERSION_ID) < 0) {//服务器的版本号大于本机获取版本号
                    if (mType == 0) {
                        progressDialog.dismiss();
                    }
                    while (Constants.CurrentContext == null) ;//这个是怕弹窗的时机不对
                    new AlertDialog.Builder(Constants.CurrentContext)
                            .setTitle("软件版本更新")
                            .setMessage("检查到有新版本更新，建议您下载\n更新内容 :\n" + description)
                            .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    if (!Utils.hasAllFilesAccess()) {
                                        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(Constants.CurrentContext);
                                        builder.setTitle("提示");
                                        builder.setMessage("为成功下载最新包，请打开文件所有权限,是否打开？");
                                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                                                Uri uri = Uri.fromParts("package", Constants.CurrentContext.getPackageName(), null);
                                                intent.setData(uri);
                                                Constants.CurrentContext.startActivity(intent);
                                            }
                                        });
                                        builder.setNeutralButton("否", null);
                                        builder.show(); //调用show()方法来展示对话框
                                    } else {
                                        new UpdateAppManager(Constants.CurrentContext).execute();
                                    }
                                }
                            }).create().show();
                } else {
                    if (mType == 0) {
                        progressDialog.dismiss();
                        new AlertDialog.Builder(Constants.CurrentContext)
                                .setTitle("提示")
                                .setMessage("您是最新版本，无需更新！")
                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).create().show();
                    }
                }
            } else {
                if (mType == 0) {
                    progressDialog.dismiss();
                    new AlertDialog.Builder(Constants.CurrentContext)
                            .setTitle("警告")
                            .setMessage("获取版本号失败，请检查是否给予软件许可！")
                            .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                }
            }
        }
    }

    private void getVersionId(String Url) throws IOException {
        HttpURLConnection con = null;
        try {
            URL url = new URL(Url);
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(60000);
            con.setReadTimeout(60000);
            con.setRequestMethod("GET");
            con.setRequestProperty("client", "app");
            InputStream inputStream = con.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            String jsonString = new String(data);
            JSONObject jsonObj;
            jsonObj = new JSONObject(jsonString);
            JSONObject d = jsonObj.getJSONObject("data");
            Constants.VERSION_ID = d.getString("version");
            Constants.DOWNLOAD_URL = d.getString("downurl");
            description = d.getString("description").replace("|", "\n");
        } catch (Exception e) {
            Log.e("版本更新", "最新版本:" + e);
        } finally {
            if (con != null)
                con.disconnect();
        }
    }

}
